/**
 * @page: 合同管理页面
 * @author: fj
 */
import { useEffect, useState, useMemo } from 'react';
import HeaderTab from '@/components/CommonTab';
import ApplyPeriod from './component/ApplyPeriod';
import FormRender from '@/components/FormRender';
import OperaBtnRender from '@/components/OperaBtnRender';
import ContractStop from './component/ContractStop';
import ContractTable from './component/ContractTable';
import { notification } from 'antd';
import { useResize } from '@/hooks/useResize';
import { getFormItem, tabArr } from './config.js';
import {
  queryContractList,
  contractApply,
  contractReApply,
  hasFinish,
  contractClose,
} from './service';



const ContractManager = () => {
  // 当前tab
  const [type, setType] = useState('0');
  // 搜索数据
  const [query, setQuery] = useState({});
  //列表数据
  const [data, setData] = useState([]);

  //是否是重新申请
  const [isReApply, setIsReApply] = useState(false);

  //列表单条数据
  const [recordData, setRecordData] = useState({});
  //申请终止
  const [stopVisible, setStopVisible] = useState(false);
  //分页数据
  const [pages, setPages] = useState({
    current: 1,
    total: 0,
    pageSize: 20,
  });
  //申请账单的弹窗
  const [visible, setVisible] = useState(false);

  //监听变更
  const { el: headerEl, height: headerHeight } = useResize();

  //表单数据
  const formArr = useMemo(() => {
    return getFormItem();
  }, [])

  useEffect(() => {
    getContractList();
  }, [type, query, pages.current, pages.pageSize]);

  // 获取合同列表
  const getContractList = async () => {
    START_LOADING();
    setData([]);
    const { success, data = {} } = await queryContractList({
      ...query,
      status: type != '0' ? type : undefined,
      storeIds: query.storeIds?.join(',') || undefined,
      current: pages.current,
      size: pages.pageSize,
    });
    if (success) {
      const { records = [], total = 0 } = data;
      setData(records);
      setPages({
        ...pages,
        total,
      });
    }
    END_LOADING();
  };

  //账期申请提交
  const handleOk = async (val, storeObj) => {
    START_LOADING();
    let contractcommonApply = contractApply;
    if (isReApply) {
      contractcommonApply = contractReApply;
    }
    const { success } = await contractcommonApply({
      ...val,
      contractId: isReApply ? recordData.contractId : undefined,
      memberId: storeObj.value ? storeObj.value : recordData.memberId,
      storeId: storeObj.key ? storeObj.key : recordData.storeId,
      storeName: storeObj.children ? storeObj.children : recordData.storeName,
      timePeriod: Number(val.timePeriod),
    });
    if (success) {
      setVisible(false);
      setType('1');
      getContractList({}, type, {
        ...pages,
        current: 1,
      });
    }
    END_LOADING();
  };

  //申请账期弹窗
  const showApplyPeriodModal = () => {
    setVisible(true);
    setRecordData({});
    setIsReApply(false);
  };

  // tab组件数据
  const HeaderTabProps = {
    type,
    data: tabArr,
    //tab改变
    onChange(val) {
      setType(val);
    },
  };

  // 列表组件数据
  const ContractListProps = {
    type,
    data,
    pages,
    setPages,
    headerHeight,
    setRecordData,
    showApplyPeriodModal() {
      setVisible(true);
      setIsReApply(true);
    },
    handleClickStop(record) {
      handleStop(record);
      setRecordData(record);
    }, // 终止
  };

  // 申请账期弹窗数据
  const ApplyPeriodModalProps = {
    visible,
    recordData,
    handleCancel() {
      setVisible(false);
    },
    handleOk,
  };

  //表单渲染组件
  const FormRenderProps = {
    query,
    formArr,
    formConfig: {
      name: 'contract-manage-form',
      style: { marginBottom: '16px' }
    },
    clickSearch(val) {
      setPages({
        ...pages,
        current: 1
      });
      setQuery(val);
    },
    clickReset() {
      setPages({
        ...pages,
        current: 1
      });
      setQuery({});
    },
  }

  //申请终止弹窗数据
  const stopProps = {
    stopVisible,
    handleOk(val) {
      handleStopOk(val);
    },
    handleCancel() {
      setStopVisible(false);
    },
  };

  //账期终止提交
  const handleStopOk = async (val) => {
    START_LOADING();
    const { success } = await contractClose({
      closeMessage: val.closeMessage,
      contractId: recordData.contractId,
    });
    if (success) {
      setStopVisible(false);
      getContractList({}, type, {
        ...pages,
        current: 1,
      });
    }
    END_LOADING();
  };

  //账期终止
  const handleStop = async (record) => {
    START_LOADING();
    const { success, data = {} } = await hasFinish({
      contractId: record.contractId,
    });
    if (success) {
      if (data) {
        notification.open({
          description: '账期订单未完结，请去尽快拿货或作废返审核',
        });
      } else {
        setStopVisible(true);
        getContractList(query, type, pages);
      }
    }
    END_LOADING();
  };

  //操作按钮
  const btnArr = [
    { elType: 'button', text: '申请账期', onClick: showApplyPeriodModal }
  ]

  return (
    <>
      <HeaderTab {...HeaderTabProps} />
      <div ref={headerEl}>
        <FormRender {...FormRenderProps} />
      </div>
      <div className='global-page-wrap'>
        <OperaBtnRender style={{ marginBottom: '12px' }} btnArr={btnArr} />
        <ContractTable {...ContractListProps} />
      </div>
      {visible && <ApplyPeriod {...ApplyPeriodModalProps} />}
      {stopVisible && <ContractStop {...stopProps} />}
    </>
  );
};

export default ContractManager;
